package com.zjp.mg.callback;

import com.github.javafaker.Faker;
import com.zjp.mg.core.MgConstants;
import com.zjp.mg.core.MgEntity;
import org.bson.Document;
import org.springframework.data.mongodb.core.mapping.event.BeforeSaveCallback;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Locale;
import java.util.Objects;

@Component
public class MgCallback<T> implements BeforeSaveCallback<T> {


    @Override
    public T onBeforeSave(T entity, Document document, String collection) {
        MgEntity mgEntity = entity instanceof MgEntity ? ((MgEntity) entity) : null;
        if (Objects.nonNull(mgEntity)) {
            Faker faker = new Faker(Locale.CHINA);
            mgEntity.setCreateBy(faker.name().name());
            mgEntity.setCreateTime(new Date());
            mgEntity.setIsDeleted(MgConstants.IS_DELETED_EXIST);
        }


        return entity;
    }


}
